import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import ClassManage from '../views/ClassManage.vue'
import StudentManage from '../views/StudentManage.vue'
import DeptManage from '../views/DeptManage.vue'
import EmpManage from '../views/EmpManage.vue'
import Login from '../views/Login.vue'

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/login', component: Login },
  { path: '/home', component: Home },
  { path: '/class-manage', component: ClassManage },
  { path: '/student-manage', component: StudentManage },
  { path: '/dept-manage', component: DeptManage },
  { path: '/staff-manage', component: EmpManage }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫，判断是否需要登录
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果访问的是登录页，直接放行
  if (to.path === '/login') {
    next()
    return
  }
  
  // 如果没有token，重定向到登录页
  if (!token) {
    next('/login')
    return
  }
  
  // 其他情况放行
  next()
})

export default router 